package org.viva.service.cms;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;
import org.viva.core.dao.BaseDAO;
import org.viva.entity.cms.Tag;

@Service("tagService")
public class TagService {

    @Resource
    private BaseDAO<Tag> dao;

    @SuppressWarnings("unchecked")
    public List<Tag> getTags(Map<String, Object> param) {
        Criteria criteria = dao.getCurrentSession().createCriteria(Tag.class);
        criteria.addOrder(Order.desc("articleCount"));
        criteria.setFirstResult(0);
        int rows = 10;
        try {
            rows = Integer.parseInt(param.get("rows").toString());
        } catch (Exception e) {
        }
        criteria.setMaxResults(rows);
        return criteria.list();
    }

    public void setTags(String tags) {
        if (tags == null) return;
        for (String tag : tags.split("[,]")) {
            if ("".equals(tag.trim())) continue;
            Tag t = dao.get("from Tag where name = ?", new String[] { tag });
            if (t != null) {
                SQLQuery query = dao.getCurrentSession().createSQLQuery("SELECT COUNT(1) FROM CMS_CONTENT WHERE TAGS LIKE '%" + tag + "%'");
                int i = Integer.parseInt(query.uniqueResult() + "");
                t.setArticleCount(i);
                dao.update(t);
            } else {
                t = new Tag();
                t.setName(tag);
                t.setArticleCount(1);
                dao.save(t);
            }
        }
    }

    public void clearTags() {
        List<Tag> list = dao.find("from Tag");
        for (Tag t : list) {
            try {
                SQLQuery query = dao.getCurrentSession().createSQLQuery("SELECT COUNT(1) FROM CMS_CONTENT WHERE TAGS LIKE '%" + t.getName() + "%'");
                int i = Integer.parseInt(query.uniqueResult() + "");
                t.setArticleCount(i);
                dao.update(t);
            } catch (Exception e) {
            }
        }
    }

}
